import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
import os

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def plot_trends():
    conferences = ['aaai', 'iccv', 'icml']
    plt.figure()
    
    for conf in conferences:
        df = pd.read_csv(f'output/{conf}_papers.csv')
        yearly_counts = df['Year'].value_counts().sort_index()
        plt.plot(yearly_counts.index, yearly_counts.values, 'o-', label=conf.upper())
    
    plt.title("各会议论文数量趋势 (2020-2025)")
    plt.xlabel("年份")
    plt.ylabel("论文数量")
    plt.legend()
    plt.grid(True)
    plt.savefig('output/trend.png')
    plt.show()


def analyze_keywords():
    conferences = ['aaai', 'iccv', 'icml']
    stop_words = {'the', 'and', 'for', 'with', 'of', 'in', 'a', 'to', 'on', 'by'}
    
    for conf in conferences:
        try:
            df = pd.read_csv(f'output/{conf}_papers.csv')
            
            all_words = []
            for title in df['Title']:
                words = [word.lower() for word in str(title).split() 
                        if word.isalpha() and word.lower() not in stop_words and len(word) > 3]
                all_words.extend(words)
            
            top_words = Counter(all_words).most_common(20)
            print(f"\n{conf.upper()}会议高频关键词:")
            for word, count in top_words:
                print(f"{word}: {count}次")
            
            plt.figure(figsize=(10, 5))
            words, counts = zip(*top_words)
            plt.barh(words, counts)
            plt.title(f"{conf.upper()}会议论文高频关键词")
            plt.tight_layout()
            plt.savefig(f'output/{conf}_keywords.png')
            plt.show()
            
        except:
            print(f"{conf}数据分析失败")
            continue

def simple_prediction():
    conferences = ['aaai', 'iccv', 'icml']
    
    for conf in conferences:
        df = pd.read_csv(f'output/{conf}_papers.csv')
        yearly_counts = df['Year'].value_counts().sort_index()
                
        years = [int(y) for y in yearly_counts.index]
        counts = yearly_counts.values
        n = len(years)
            
        sum_x = sum(years)
        sum_y = sum(counts)
        sum_xy = sum(x*y for x,y in zip(years, counts))
        sum_x2 = sum(x*x for x in years)
            
        a = (n*sum_xy - sum_x*sum_y) / (n*sum_x2 - sum_x*sum_x)
        b = (sum_y - a*sum_x) / n
            
        next_year = max(years) + 1
        pred = round(a * next_year + b)
            
        print(f"\n{conf.upper()}会议预测结果:")
        print(f"2020-{max(years)}年数据: {dict(zip(years, counts))}")
        print(f"预测{next_year}年论文数量: {pred}篇")
            

if __name__ == '__main__':
    if not os.path.exists('output'):
        os.makedirs('output')
    
    print("=== 开始分析 ===")
    plot_trends()
    analyze_keywords()
    simple_prediction()
    print("=== 分析完成 ===")